using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;

public class Enemy : MonoBehaviour
{
    //Value
    public float movespeed = 3;
    private Vector3 bulletEulerAngles;
    private float v;
    private float h;

    //Reference
    private SpriteRenderer sr;
    public Sprite[] tankSprite; //up right down left
    public GameObject bullletPrefab;
    public GameObject explosionPerfab;

    //Count
    private float timeVal;
    private float timeValChangeDirection = 4;
    
    private void Awake()
    {
        sr = GetComponent<SpriteRenderer>();
    }

    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        //Attack CD
        if (timeVal >= 3f)
        {
            PlayerAttack();
        }
        else
        {
            timeVal += Time.deltaTime;
        }
    }

    private void FixedUpdate()
    {
        Playermove();
    }

    //The ways of attack of players
    private void PlayerAttack()
    {
        Instantiate(bullletPrefab, transform.position, Quaternion.Euler(transform.eulerAngles + bulletEulerAngles));
        timeVal = 0;
    }

    //The ways of moving of players
    private void Playermove()
    {
        if (timeValChangeDirection>=4)
        {
            int num = Random.Range(0,8);
            if (num > 5)
            {
                v = -1;
                h = 0;
            }
            else if (num == 0)
            {
                v = 1;
                h = 0;
            }
            else if (num > 0 && num<= 2)
            {
                h = -1;
                v = 0;
            }
            else if (num > 2 && num <= 4)
            {
                h = 1;
                v = 0;
            }
            timeValChangeDirection = 0;
        }
        else
        {
            timeValChangeDirection += Time.fixedDeltaTime;
        }

        transform.Translate(Vector3.up * v * movespeed * Time.fixedDeltaTime, Space.World);

        if (v < 0)
        {
            sr.sprite = tankSprite[2];
            bulletEulerAngles = new Vector3(0, 0, -180);
        }

        else if (v > 0)
        {
            sr.sprite = tankSprite[0];
            bulletEulerAngles = new Vector3(0, 0, 0);
        }

        if (v != 0)
        {
            return;
        }

        transform.Translate(Vector3.right * h * movespeed * Time.fixedDeltaTime, Space.World);
        if (h < 0)
        {
            sr.sprite = tankSprite[3];
            bulletEulerAngles = new Vector3(0, 0, 90);
        }

        else if (h > 0)
        {
            sr.sprite = tankSprite[1];
            bulletEulerAngles = new Vector3(0, 0, -90);
        }
    }

    //Die
    private void Playerdie()
    {
        //Explode
        Instantiate(explosionPerfab, transform.position, transform.rotation);
        //Die
        Destroy(gameObject);
    }
}

